var sdkVersion = "1.0.0",
  downNum = 0,
  uploadNum = 0;

window.onload = function () {
  let selected = "";
  let downloadIndex = 0;
  // let stsData = {};
  let videoUrls = [];
  $("body").append(
    `<select id="ageSelect" style='z-index:99'>
      <option value="">请选择</option>
      <option value="1">青榕1</option>
      <option value="2">青榕2</option>
      <option value="3">思阅</option>
      <option value="4">海南俊秀</option>
    </select>`
  );
  $("body").append(`<p class='tip-dec1' id='tip-dec1'></p>`);
  $("body").append(`<p class='tip-dec2' id='tip-dec2'></p>`);
  $("body").append(
    '<button id="ys-btn1" class="ys-btn">adxray-自动采集</button>'
  );

  $("body").on("click", "#ys-btn1", function () {
    if (selected === "") {
      alert("请选择使用类型");
      return;
    }
    // chrome.storage.local.clear();
    autoCollection();
  });

  $(document).ready(function () {
    // 当选择框的值发生变化时触发事件
    $("#ageSelect").change(function () {
      selected = $(this).val();
    });
  });

  function consoleError(error) {
    if (window.SLS_Tracker) {
      const tracker = new SLS_Tracker({
        host: "cn-hangzhou.log.aliyuncs.com",
        project: "google-plugin", // Project名称。
        logstore: "video-adxray", // Logstore名称。
        topic: error.type, // 自定义日志主题。
        tags: {
          from: "sdk",
        },
      });
      const params = {
        ...error,
        version: sdkVersion, //外部跳入标识
      };
      console.log("错误上报信息", params);
      tracker.send(params);
    }
  }

  async function autoCollection() {
    // try {
    //   // 获取 TOS 的 STS 数据
    //   stsData = await getLianShanOssSts();
    //   console.log("STS data:", stsData);
    // } catch (error) {
    //   // 处理获取 STS 数据失败的情况
    //   console.error("Failed to get STS data:", error);
    //   return;
    // }

    const elements = document.querySelectorAll(".css-edu4qc");
    videoUrls = await fetchVideoData(elements);
    console.log(videoUrls);
    // 采集完数据关闭弹框
    const close = document.querySelectorAll(".adxray-app-modal-close");
    close[0].click();
    await getVideoList();
  }

  async function getVideoList() {
    var downloadPromises = [];
    // 使用循环来限制同时下载的视频数量为 2 个
    while (videoUrls.length && downloadPromises.length < 1) {
      var videoUrl = videoUrls.shift(); // 获取并移除数组中的第一个视频链接
      var downloadPromise = downloadVideo(videoUrl); // 下载视频并获取 Promise 对象
      console.log("downloadPromise", downloadPromise);
      downloadPromises.push(downloadPromise); // 将 Promise 对象添加到数组中
    }

    // 等待所有下载任务完成
    await Promise.all(downloadPromises);
    // 如果还有剩余视频链接，则递归调用 getVideoList() 继续下载
    if (videoUrls.length) {
      await getVideoList();
    }
  }

  function downloadVideo(videoInfo) {
    return new Promise((resolve, reject) => {
      console.log("视频下载");
      const { url: videoUrl } = videoInfo;
      // 发送 HTTP 请求下载视频内容
      var xhr = new XMLHttpRequest();
      xhr.open("GET", videoUrl, true);
      xhr.responseType = "blob"; // 返回二进制数据
      // 监听加载完成事件
      xhr.onload = async function (event) {
        if (xhr.status !== 200) {
          // 处理非200状态码的情况
          consoleError({ type: "down-error-status", error: xhr });
          reject(
            new Error(`Failed to download video, status code: ${xhr.status}`)
          );
          return;
        }
        try {
          var blob = xhr.response;
          // 创建一个隐藏的 <a> 标签用于下载视频
          var a = document.createElement("a");
          // 使用视频链接的文件名作为下载文件的名称
          var fileName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);
          a.href = window.URL.createObjectURL(blob);
          // 设置下载属性，指定文件名
          a.download = fileName + ".mp4";
          // 将 <a> 标签添加到文档中
          document.body.appendChild(a);
          // 模拟点击 <a> 标签进行下载
          a.click();
          // 下载完成后移除 <a> 标签
          await new Promise((resolve) => setTimeout(resolve, 5000));
          document.body.removeChild(a);
          resolve();
          // 创建一个 FormData 对象
          var formData = new FormData();
          // // 将视频文件添加到 FormData 对象中
          formData.append("file", blob, fileName);
          const formDataObject = formDataToObject(formData);
          downNum++;
          console.log("下载好了 downNum", downNum);
          document.getElementById(
            "tip-dec1"
          ).innerHTML = `已经下载：${downNum}/${
            document.querySelectorAll(".css-edu4qc").length
          }`;
          await uploadToTOS(formDataObject, videoInfo);
        } catch (error) {
          console.log("Failed to download video:", error);
          reject(error);
          consoleError({ type: "down", error: error });
        }
      };
      xhr.onerror = function (error) {
        // 处理网络错误（但可能不包括 net::ERR_NETWORK_IO_SUSPENDED）
        console.log("网络错误", error);
        consoleError({ type: "down-onerror", ...error });
        reject("Network error");
      };
      // 发送请求
      xhr.send();
    });
  }

  async function fetchVideoData(elements) {
    const videoList = [];
    let flage = 1;
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      // 模拟点击操作
      element.click();
      // 等待9s-10s页面加载完成
      await new Promise((resolve) =>
        setTimeout(resolve, Math.floor(Math.random() * 1001) + 3000)
      );
      const imgElement = $(element).find(".css-1b4j5td img");
      const text = $(element).find(".afO4r");
      const videoTags = document.getElementsByTagName("video");
      const videoUrl = videoTags[0].src;
      const videoDuration = videoTags[0].duration;
      console.log(videoDuration);
      if (isNaN(videoDuration)) {
        i--;
        console.log("重复当前的");
        if (flage > 4) {
          alert("当前网络环境较慢，建议稍后再下载");
          console.log("当前网络环境较慢，建议稍后再下载");
          consoleError({ type: "down-slow-network" });
        }
        flage++;
        continue;
      }
      flage = 1;
      console.log("flage");
      const size = `${videoTags[0].videoWidth} * ${videoTags[0].videoHeight}`;
      console.log($("a.adxray-app-typography span").text());
      console.log($(".css-1b4j5td img").attr("src"));
      console.log($("span.css-1sfst9 span").text());

      console.log($(element).find(".css-1b4j5td img"));
      console.log($("a.adxray-app-typography css-1sfst9").text());
      // 获取视频数据
      const videoData = {
        name: $("a.adxray-app-typography span").text(),
        cover: $(".css-1b4j5td img").attr("src"),
        goods_name: $("a.adxray-app-typography span").text(),
        title: $("a.adxray-app-typography span").text(),
        like_num: text.eq(1).text(),
        share_num: text.eq(3).text(),
        save_num: 0,
        commit_num: text.eq(2).text(),
        adtext: $(".css-11iixtg")[i]?.innerText || "",
        url: videoUrl,
        video_length: videoDuration,
        admin_type: selected,
        size,
      };
      // 将视频数据存入videoList
      videoList.push(videoData);
    }

    return videoList;
  }

  // 分片上传到 TOS
  async function uploadToTOS(formData, videoData) {
    const md5 = await getMd5Code(formData);
    const stsData = await getLianShanOssSts();
    let client = new TOS({
      region: stsData.data.region, // bucket 所在地址，我的是 华北2北京
      secure: true,
      accessKeyId: stsData.data.access_key_id, // 查看你自己的阿里云KEY
      accessKeySecret: stsData.data.access_key_secret, // 查看自己的阿里云KEYSECRET
      bucket: stsData.data.bucket, //你的 TOS bucket 名称
      stsToken: stsData.data.sts_token,
    });

    let fileType = formData.file.name.split("?")[0];
    let uploadId = null;
    const {
      data: { UploadId },
    } = await client.createMultipartUpload({
      key: `ad_material/${fileType}`,
    });
    uploadId = UploadId;
    // 每个 Part 的大小是 8M
    const PART_SIZE = 8 * 1024 * 1024;
    const uploadPartRes = [];
    // 串行上传每个 Part
    for (let i = 0; i * PART_SIZE < formData.file.size; ++i) {
      const { data } = await client.uploadPart({
        key: `ad_material/${fileType}`,
        partNumber: i + 1,
        body: formData.file.slice(
          i * PART_SIZE,
          Math.min((i + 1) * PART_SIZE, formData.file.size)
        ),
        uploadId: uploadId,
      });
      uploadPartRes[i] = data.ETag;
    }

    const result = await client.completeMultipartUpload({
      key: `ad_material/${fileType}`,
      parts: uploadPartRes.map((eTag, idx) => ({
        eTag,
        partNumber: idx + 1,
      })),
      uploadId: uploadId,
    });
    if (result.statusCode === 200) {
      uploadNum++;
      console.log("上传 upload", uploadNum);
      document.getElementById("tip-dec2").innerHTML = `已经上传：${uploadNum}/${
        document.querySelectorAll(".css-edu4qc").length
      }`;
      getVideoData(videoData, result.data.Location, md5, formData);
      return;
    }
    consoleError({ type: "upload", error: result });
    // 这里是你具体的上传逻辑，使用 TOS 客户端进行分片上传
  }

  function formDataToObject(formData) {
    const object = {};
    formData.forEach((value, key) => {
      // 检查键是否已经存在，如果存在，则将值转换为数组
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        if (!Array.isArray(object[key])) {
          object[key] = [object[key]];
        }
        object[key].push(value);
      } else {
        object[key] = value;
      }
    });
    return object;
  }

  async function getMd5Code(options) {
    return new Promise((resolve, reject) => {
      let fileReader = new FileReader();
      let dataFile = options.file;
      let spark = new SparkMD5(); // 创建md5对象（基于SparkMD5）

      fileReader.onload = (e) => {
        try {
          spark.appendBinary(e.target.result);
          let md5 = spark.end();
          resolve(md5);
        } catch (error) {
          reject(error);
        }
      };

      fileReader.onerror = (error) => {
        reject(error);
      };

      fileReader.readAsBinaryString(dataFile);
    });
  }
  function getVideoData(videoData, url, md5, options) {
    let dataFile = options.file;
    const newData = {
      name: videoData.name, // 剧名
      cover: videoData.cover, // 视频图片
      url: url, // 获取素材网站地址
      video_url: url, // 获取素材网站地址
      type: 1, // 素材类型 0:图片 1:视频 2三小图
      source: 1, // 素材来源 0 抖音 1 adxary(web网站)
      title: videoData.name, // 素材标题
      goods_name: videoData.name, // 商品名（剧名）
      like_num: videoData.like_num, // 点赞数
      share_num: videoData.share_num, // 分享数
      save_num: videoData.save_num, // 收藏数
      commit_num: videoData.commit_num, // 评论数
      is_upload: 1, // 是否有上传到连山云过 0:没有（默认） 1:有
      is_filter: 1, // 是否过滤 0:不过滤 1:过滤（一直找不到信息的情况可以进行过滤）
      file_size: (dataFile.size / 1024 / 1024).toFixed(2), // 文件大小
      video_length: videoData.video_length, // 视频时长
      signature: md5,
      adtext: videoData.adtext,
      admin_type: videoData.admin_type,
      size: videoData.size, // 视频尺寸
      version: "1.0.0",
    };
    console.log(videoData);
    console.log("videoData");
    console.log(newData);
    setMaterialPacketCapture(newData);
  }

  function getVideoDuration(file) {
    return new Promise((resolve, reject) => {
      const video = document.createElement("video");
      video.src = URL.createObjectURL(file);
      video.onloadedmetadata = () => {
        const duration = video.duration;
        URL.revokeObjectURL(video.src);
        resolve(duration);
      };
      video.onerror = () => {
        reject(new Error("无法读取视频文件"));
      };
    });
  }

  function getLianShanOssSts() {
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "https://merchant.tmtmz.cn/merchant/common/get_lian_shan_oss_sts",
        method: "GET",
        success: function (response) {
          // 请求成功，将响应数据传递给 resolve 函数
          resolve(response);
        },
        error: function (xhr, status, error) {
          // 请求失败，将错误信息传递给 reject 函数
          reject(error);
          consoleError({
            type: "getLianShanOssSts",
            error: error,
            xhr: xhr,
            status: status,
          });
        },
      });
    });
  }
  // 抖音视频推送接口
  function setMaterialPacketCapture(data) {
    downloadIndex++;
    // 获取当前页面有多少个素材
    if (document.querySelectorAll(".css-edu4qc").length === downloadIndex) {
      var audio = new Audio(
        "https://img.tukuppt.com/newpreview_music/09/00/79/5c894fae75f3028946.mp3"
      );
      const timer = setTimeout(() => {
        audio.play();
        // 下载完成后初始化
        downloadIndex = 0;
        videoUrls = [];
        clearTimeout(timer);
        alert("采集完成！");
      }, 5000);
    }

    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "https://api.tmtmz.cn/open/material_packet_capture",
        method: "POST",
        data: data,
        success: function (response) {
          // 请求成功，将响应数据传递给 resolve 函数
          resolve(response);
        },
        error: function (xhr, status, error) {
          // 请求失败，将错误信息传递给 reject 函数
          reject(error);
          consoleError({
            type: "setMaterialPacketCapture",
            error: error,
            xhr: xhr,
            status: status,
          });
        },
      });
    });
  }
};
